import { defineStore } from 'pinia'

export interface Song {
  id?: string | number
  title: string
  artist: string
  duration: string
  url: string
  cover?: string
  source: 'local' | 'database' | 'external'
}

export interface MusicState {
  isPlaying: boolean
  isExpanded: boolean
  currentTime: number
  duration: number
  volume: number
  currentSongIndex: number
  playlist: Song[]
  audioElement: HTMLAudioElement | null
  isLoading: boolean
  error: string | null
}

export const useMusicStore = defineStore('music', {
  state: (): MusicState => ({
    isPlaying: false,
    isExpanded: false,
    currentTime: 0,
    duration: 0,
    volume: 50,
    currentSongIndex: 0,
    playlist: [],
    audioElement: null,
    isLoading: false,
    error: null
  }),

  getters: {
    currentSong: (state): Song => state.playlist[state.currentSongIndex],
    
    progressPercentage: (state): number => {
      return state.duration > 0 ? (state.currentTime / state.duration) * 100 : 0
    },

    formattedCurrentTime: (state): string => {
      const mins = Math.floor(state.currentTime / 60)
      const secs = Math.floor(state.currentTime % 60)
      return `${mins}:${secs.toString().padStart(2, '0')}`
    },

    formattedDuration: (state): string => {
      const mins = Math.floor(state.duration / 60)
      const secs = Math.floor(state.duration % 60)
      return `${mins}:${secs.toString().padStart(2, '0')}`
    }
  },

  actions: {
    // 初始化音频元素
    initAudio() {
      if (typeof window === 'undefined') return
      
      this.audioElement = new Audio()
      this.audioElement.volume = this.volume / 100
      
      // 绑定事件监听器
      this.audioElement.addEventListener('loadedmetadata', () => {
        this.duration = this.audioElement?.duration || 0
      })
      
      this.audioElement.addEventListener('timeupdate', () => {
        this.currentTime = this.audioElement?.currentTime || 0
      })
      
      this.audioElement.addEventListener('ended', () => {
        this.isPlaying = false
        this.nextSong()
      })
      
      this.audioElement.addEventListener('play', () => {
        this.isPlaying = true
      })
      
      this.audioElement.addEventListener('pause', () => {
        this.isPlaying = false
      })
      
      // 初始化时加载默认音乐
      this.loadDefaultMusic()
    },

    // 加载默认音乐文件（从 @video/ 目录）
    async loadDefaultMusic() {
      try {
        this.isLoading = true
        this.error = null
        
        // 默认音乐文件列表（放在 @video/ 目录下）
        const defaultSongs: Song[] = [
          {
            id: 'default-1',
            title: '默认音乐 1',
            artist: '系统音乐',
            duration: '0:00',
            url: '/assets/video/default-music-1.mp3',
            source: 'local'
          },
          {
            id: 'default-2', 
            title: '默认音乐 2',
            artist: '系统音乐',
            duration: '0:00',
            url: '/assets/video/default-music-2.mp3',
            source: 'local'
          },
          {
            id: 'default-3',
            title: '默认音乐 3', 
            artist: '系统音乐',
            duration: '0:00',
            url: '/assets/video/default-music-3.mp3',
            source: 'local'
          }
        ]
        
        // 如果播放列表为空，加载默认音乐
        if (this.playlist.length === 0) {
          this.playlist = defaultSongs
        }
      } catch (error) {
        this.error = '加载默认音乐失败'
        console.error('加载默认音乐失败:', error)
      } finally {
        this.isLoading = false
      }
    },

    // 从数据库加载音乐
    async loadMusicFromDatabase() {
      try {
        this.isLoading = true
        this.error = null
        
        // 调用 API 接口获取音乐列表
        const response = await $fetch('/api/music')
        
        if (response.success && response.data) {
          const songs: Song[] = response.data.map((item: any) => ({
            id: item.id,
            title: item.title,
            artist: item.artist,
            duration: item.duration,
            url: item.url,
            cover: item.cover,
            source: 'database' as const
          }))
          
          // 将数据库音乐添加到播放列表
          this.playlist = [...this.playlist, ...songs]
        }
        
      } catch (error) {
        this.error = '从数据库加载音乐失败'
        console.error('从数据库加载音乐失败:', error)
        
        // 如果 API 调用失败，使用模拟数据作为备选
        const mockDatabaseSongs: Song[] = [
          {
            id: 'db-1',
            title: '数据库音乐 1',
            artist: '数据库艺术家',
            duration: '3:45',
            url: '/api/music/stream/1',
            cover: '/api/music/cover/1',
            source: 'database'
          },
          {
            id: 'db-2',
            title: '数据库音乐 2', 
            artist: '数据库艺术家',
            duration: '4:12',
            url: '/api/music/stream/2',
            cover: '/api/music/cover/2',
            source: 'database'
          }
        ]
        
        this.playlist = [...this.playlist, ...mockDatabaseSongs]
      } finally {
        this.isLoading = false
      }
    },

    // 刷新播放列表（重新加载所有音乐）
    async refreshPlaylist() {
      this.playlist = []
      await this.loadDefaultMusic()
      await this.loadMusicFromDatabase()
    },

    // 切换播放器展开状态
    toggleExpanded() {
      this.isExpanded = !this.isExpanded
    },

    // 播放/暂停切换
    togglePlayPause() {
      if (!this.audioElement) return
      
      if (this.isPlaying) {
        this.audioElement.pause()
      } else {
        this.audioElement.play()
      }
    },

    // 播放指定歌曲
    playSong(index: number) {
      this.currentSongIndex = index
      this.playCurrentSong()
    },

    // 播放当前歌曲
    playCurrentSong() {
      if (!this.audioElement) return
      
      this.audioElement.src = this.currentSong.url
      this.audioElement.load()
      this.audioElement.play()
    },

    // 上一首
    previousSong() {
      this.currentSongIndex = this.currentSongIndex > 0 
        ? this.currentSongIndex - 1 
        : this.playlist.length - 1
      this.playCurrentSong()
    },

    // 下一首
    nextSong() {
      this.currentSongIndex = this.currentSongIndex < this.playlist.length - 1 
        ? this.currentSongIndex + 1 
        : 0
      this.playCurrentSong()
    },

    // 跳转到指定时间
    seekTo(time: number) {
      if (!this.audioElement) return
      this.audioElement.currentTime = time
      this.currentTime = time
    },

    // 更新音量
    updateVolume(volume: number) {
      this.volume = volume
      if (this.audioElement) {
        this.audioElement.volume = volume / 100
      }
    },

    // 添加歌曲到播放列表
    addSong(song: Song) {
      this.playlist.push(song)
    },

    // 从播放列表移除歌曲
    removeSong(index: number) {
      if (index >= 0 && index < this.playlist.length) {
        this.playlist.splice(index, 1)
        if (this.currentSongIndex >= this.playlist.length) {
          this.currentSongIndex = Math.max(0, this.playlist.length - 1)
        }
      }
    },

    // 清理资源
    cleanup() {
      if (this.audioElement) {
        this.audioElement.pause()
        this.audioElement = null
      }
    }
  }
})
